﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Threading;
using CloudStorageLight.Web.Models;
using CloudStorageLight.Core;
using System.Security.Principal;
using System.Diagnostics;
using System.IO;
using CloudStorageLight.Core.Web;
using DropNet;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.WsFederation;
using Microsoft.Owin.Security;
using System.Security.Claims;

namespace CloudStorageLight.Web.Controllers
{
    public class HomeController : FilesControllerBase
    {
        protected override BlobService CreateBlobService()
        {
            return new BlobService();
        }

        public ApplicationUserManager UserManager
        {
            get
            {
                _userManager = _userManager ?? OwinContextExtensions.GetUserManager <ApplicationUserManager>(HttpContext.GetOwinContext());
                return _userManager;
            }
            private set
            {
                _userManager = value;
            }
        }
        private ApplicationUserManager _userManager;

        protected override BlobUser GetCurrentUser()
        {
            if (_user == null)
            {
                _user = BasicAuthenticateUtil.GetCurrentUser();
            }
            return _user;
        }
        private BlobUser _user;

        public bool DisableLogin { get { return SystemSettings.Instance.DisableLogin; } }

        [AllowAnonymous]
        public ActionResult Root()
        {
            if (!this.HttpContext.User.Identity.IsAuthenticated)
            {
                if (!DisableLogin)
                {
                    return Redirect("~/Account/Login");
                }
                else
                {
                    return new HttpStatusCodeResult(401);
                }

            }
            if (SystemSettings.Instance.MultiDomain)
            {
                var account = BlobService.GetCurrentCloudAccount();
                if (account == null)
                {
                    var claims = ((System.Security.Claims.ClaimsIdentity)System.Web.HttpContext.Current.User.Identity).Claims;
                    var cloudAccountClaim = claims.FirstOrDefault(x => x.Type == "CloudAccount");
                    if (cloudAccountClaim == null) return Redirect("~/Account/Login");
                    var url = Url.RouteUrl("files", new { domain = cloudAccountClaim.Value, id = "/" });
                    return Redirect(url);
                }
                else
                {
                    var url = Url.RouteUrl("files", new { domain = account.AccountName, id = "/" });
                    return Redirect(url);
                }
            }
            else
            {
                var url = Url.RouteUrl("files", new { id = "/" });
                return Redirect(url);
            }
        }

        public override async Task<ActionResult> Index(string id = "", string snapshot = "current", string mode = null, string baseVersion=null, string passcode=null, FormCollection fc=null)
        {
            //後ろ空白トリム対策
            var rootPath = Url.RouteUrl("files", new { id = "" });
            if (this.Request.Url.AbsolutePath.Length > rootPath.Length+1)
            {
                id = BlobUtil.UnescapeDataString(this.Request.Url.AbsolutePath.Substring(rootPath.Length + 1));
            }
            var svc = CreateBlobService();
            var user = GetCurrentUser();
            var auth = svc.GetCustomAuth(id);
            if (!this.HttpContext.User.Identity.IsAuthenticated && auth == null && !await svc.CanReadAsync(user, "/" + id.TrimStart('/')))
            {
                if (!DisableLogin) return RedirectToAction("Login", "Account", new { returnUrl = Request.Url.AbsolutePath });
                return new HttpStatusCodeResult(401);
            }

            return await base.Index(id, snapshot, mode, baseVersion, passcode, fc);
        }

    }
}